package com.huaxindata.im.util;

import android.os.AsyncTask;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
* 下载的一个工具类，采用单例模式来获取实例
 * 下载采用asynctask来进行，通过downloadListenner接
 * 口在主线程中回调更新ui
*@author:guokailin
*time:2017/6/26 16:51
*/
public class DownloadManager {

    private static DownloadManager sInstance=new DownloadManager();

    //私有化构造方法，通过单例模式获取对象实例
    private DownloadManager(){
        super();
    }
    /**
    *
    * 单例模式获取下载管理器对象
    *@author:guokailin
    *time:2017/6/26 16:25
    */
    public static DownloadManager getInstance(){
        return sInstance;
    }

    /**
     *
     * 下载文件
     *@author:guokailin
     *time:2017/6/26 14:16
     */
    public void downloadFile(String url,String savePath,DownloadListener downloadListener){
        DownloadAsyncTask task = new DownloadAsyncTask(downloadListener);
        task.execute(url,savePath);
    }

    public interface DownloadListener {
        void onSuccess(String savePath);

        void onError(String error);

        void onProgress(int percent);
    }
    /**
     *  进行异步下载的异步任务,params[0]为下载的url,params[1]为保存的路径
     *  下载完成后返回文件路径
     *@author:guokailin
     *time:2017/6/26 14:55
     */
    private static class DownloadAsyncTask extends AsyncTask<String,Integer,Integer>{
        private DownloadListener mDownloadListener;

        private static File DEFAULT_PATH;//默认的保存路径

        public DownloadAsyncTask(DownloadListener downloadListener){
            this.mDownloadListener = downloadListener;
        }
        @Override
        protected void onPreExecute() {
            if (DEFAULT_PATH == null) {
                DEFAULT_PATH = Environment.getDataDirectory();
            }
        }
        @Override
        protected Integer doInBackground(String... params) {
            String urlStr=params[0];
            String savePath=params[1];
            if (urlStr == null) {
                return 0;
            }
            File file;
            if (savePath == null) {
                file = DEFAULT_PATH;//设置默认的下载地址
            } else {
                file = new File(savePath);
            }
            try {
                URL url=new URL(urlStr);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.connect();
                int contentLength = httpURLConnection.getContentLength();
                //这里应用了java7自动关闭流资源
                try(
                        InputStream inputStream= httpURLConnection.getInputStream();
                        FileOutputStream outputStream = new FileOutputStream(file);
                ){
                    byte[] buffer=new byte[2<<16];//每次读取64kb
                    int lenth;//每次读取的字节长度
                    int progress=0;//读取的进度
                    while ((lenth=inputStream.read(buffer))!=-1) {
                        outputStream.write(buffer,0,lenth);
                        progress+=lenth;
                        publishProgress(progress/contentLength*100);//发布下载进度到主线程
                    }
                    outputStream.flush();
                    return 1;
                } catch (Exception e) {
                    e.printStackTrace();
                    return 0;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return 0;
            } catch (IOException e) {
                e.printStackTrace();
                return 0;
            }
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            mDownloadListener.onProgress(values[0]);//在主线程更新下载进度
        }

        @Override
        protected void onPostExecute(Integer resultCode) {
            if (resultCode == 0) {
                mDownloadListener.onError("下载失败");
            } else if (resultCode == 1) {
                mDownloadListener.onSuccess(null);
            }
        }
    }
}
